from gi.repository import GdkPixbuf, GLib
import os
import threading

class CoverLoader:
    def __init__(self, cache_size=50):
        self.cache = {}
        self.cache_size = cache_size
        self.lock = threading.Lock()

    def load_cover(self, station_id, callback):
        """异步加载封面"""
        def _load_in_thread():
            cover_path = self._get_cover_path(station_id)
            
            # 检查缓存
            with self.lock:
                if station_id in self.cache:
                    pixbuf = self.cache[station_id]
                else:
                    try:
                        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                            cover_path, 128, 128
                        )
                        self._add_to_cache(station_id, pixbuf)
                    except Exception as e:
                        print(f"Error loading cover: {e}")
                        pixbuf = None
                
            # 在主线程中执行回调
            GLib.idle_add(callback, pixbuf)

        threading.Thread(target=_load_in_thread, daemon=True).start()

    def _get_cover_path(self, station_id):
        covers_dir = 'src/assets/covers'
        # 查找匹配的封面文件
        for ext in ['.png', '.jpg']:
            cover_path = os.path.join(covers_dir, f"{station_id}{ext}")
            if os.path.exists(cover_path):
                return cover_path
        return os.path.join(covers_dir, 'default.png')

    def _add_to_cache(self, station_id, pixbuf):
        with self.lock:
            if len(self.cache) >= self.cache_size:
                self.cache.pop(next(iter(self.cache)))
            self.cache[station_id] = pixbuf

    def preload_covers(self, station_ids):
        """预加载常用封面"""
        for sid in station_ids[:10]:  # 限制预加载数量
            self.load_cover(sid, lambda _: None)